package com.vehicle.common.util.thread.pool;

import lombok.Getter;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.SynchronousQueue;

/**
 * Created by yantingbin on 2017/7/29.
 */
public class ThreadPoolConfig {
    public static final int REJECTED_POLICY_ABORT = 0;
    public static final int REJECTED_POLICY_CALLER_RUNS = 2;
    //名字
    @Getter
    private String name;
    //最小线程数
    @Getter
    private int corePoolSize;
    //最大线程数
    @Getter
    private int maxPoolSize;
    //允许缓冲在队列中的任务数（0：不缓冲、负数：无限大、正数：缓冲的任务数）
    @Getter
    private int queueCapacity;
    //存活时间
    @Getter
    private int keepAliceSeconds;

    @Getter
    private int rejectedPolicy;

    public static class Builder {
        private String name;
        private int corePoolSize;
        private int maxPoolSize;
        private int queueCapacity;
        private int keepAliceSeconds;
        private int rejectedPolicy = REJECTED_POLICY_ABORT;

        public Builder(String name) {
            this.name = name;
        }

        public Builder setCorePoolSize(int corePoolSize) {
            this.corePoolSize = corePoolSize;
            return this;
        }

        public Builder setMaxPoolSize(int maxPoolSize) {
            this.maxPoolSize = maxPoolSize;
            return this;
        }

        public Builder setQueueCapacity(int queueCapacity) {
            this.queueCapacity = queueCapacity;
            return this;
        }

        public Builder setKeepAliceSeconds(long keepAliceSeconds) {
            this.keepAliceSeconds =(int) keepAliceSeconds;
            return this;
        }

        public Builder setRejectedPolicy(int rejectedPolicy) {
            this.rejectedPolicy = rejectedPolicy;
            return this;
        }

        public ThreadPoolConfig build() {
            return new ThreadPoolConfig(this);
        }
    }

    private ThreadPoolConfig(Builder builder) {
        name = builder.name;
        corePoolSize = builder.corePoolSize;
        maxPoolSize = builder.maxPoolSize;
        queueCapacity = builder.queueCapacity;
        keepAliceSeconds = builder.keepAliceSeconds;
        rejectedPolicy = builder.rejectedPolicy;
    }

    public BlockingQueue<Runnable> getQueue(){
        BlockingQueue<Runnable> blockingQueue;
        if(queueCapacity==0){
            blockingQueue=new SynchronousQueue<>();
        }else if(queueCapacity<0){
            blockingQueue=new LinkedBlockingDeque<>();
        }else{
            blockingQueue=new LinkedBlockingDeque<>(queueCapacity);
        }
        return blockingQueue;
    }
}
